/* eslint-disable semi */
/**
 * Created by JetBrains PhpStorm.
 * User: taoqili
 * Date: 12-2-20
 * Time: 上午11:19
 * To change this template use File | Settings | File Templates.
 */

(function (window, $) {
  var editor = window.editor || null;
  var dialog = window.dialog || null;
  var WebUploader = window.WebUploader || null;
  /**
     * 获取 window 的父级 window.parent
     * @returns
     */
  function getVue () {
    return window && window.parent ? window.parent : null
  }
  /**
   * 获取父级window 定义的 vueFunctions 对象中的方法
   * @param functionName
   * @returns
   */
  function getVueFunc (functionName) {
    var vue = getVue()
    if (vue && vue.vueFunctions && vue.vueFunctions[functionName]) {
      return vue.vueFunctions[functionName]
    }
    throw new Error('未找到 vue.vueFunctions 对象中的方法：' + functionName)
  }
  function getQueryVariable (variable) {
    function getQueryStr (urls = '') {
      var url = urls || (window.top.location.href.split('#')[1] || window.top.location.href);
      url = decodeURIComponent(url);
      var result = {};
      var arr = url.split('?');
      var params = arr[1] && arr[1].split('&');
      if (!params) return result;
      for (var i = 0; i < params.length; i++) {
        var item = params[i].split('=');
        item[0] = decodeURIComponent(item[0]);
        item[1] = decodeURIComponent(item[1]);
        result[item[0]] = item[1];
      }
      return result;
    }

    function getQueryString (key) {
      var after = window.top.location.search;
      if (after.indexOf('?') === -1) { return null; }
      after = after.substring(1) || window.top.location.hash.split('?')[1];
      if (after) {
        var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
        var r = after.match(reg);
        if (r != null) {
          return decodeURIComponent(r[2]);
        } else {
          return null;
        }
      }
    }
    let params = getQueryStr();
    let result = 'no_jsessionid';
    if (params[variable]) {
      result = params[variable];
    }
    if (result === 'no_jsessionid') {
      result = getQueryString(variable);
    }
    return result;
  }

  // 请求获取数据
  var request = {
    get: function (url, data, successFunc, errorFunc, completeFunc) {
      $.ajax({
        url: url,
        data: data,
        type: 'GET',
        dataType: 'json',
        beforeSend: function (request) {
          request.setRequestHeader('Authorization', getQueryVariable('jsessionid'));
        },
        success: function (data) {
          if (typeof successFunc === 'function') {
            successFunc(data);
          }
        },
        error: function (xhr, status, error) {
          if (typeof errorFunc === 'function') {
            errorFunc(xhr, status, error);
          }
        },
        complete: function (xhr, status) {
          if (typeof completeFunc === 'function') {
            completeFunc(xhr, status);
          }
        }
      })
    },
    post: function post (url, data, successFunc, errorFunc, completeFunc) {
      $.ajax({
        url: url,
        data: data,
        type: 'POST',
        dataType: 'json',
        beforeSend: function (request) {
          request.setRequestHeader('Authorization', getQueryVariable('jsessionid'));
        },
        success: function (data) {
          if (typeof successFunc === 'function') {
            successFunc(data);
          }
        },
        error: function (xhr, status, error) {
          if (typeof errorFunc === 'function') {
            errorFunc(xhr, status, error);
          }
        },
        complete: function (xhr, status) {
          if (typeof completeFunc === 'function') {
            completeFunc(xhr, status);
          }
        }
      })
    }
  }
  // 首先获取视频列表数据内容
  function renderVideoList (nparam) {
    var obj = {
      filelistDom: null,
      list: [],
      append: false,
      empty: false,
      end: false
    }

    var param = $.extend({}, obj, nparam)

    var { filelistDom, list, append, empty, end } = param;
    if (!filelistDom) {
      return;
    }

    if (empty === true) {
      // 请求结果为空的情况
      filelistDom.html('<li style="width: 100%;height: 120px;margin: 0;padding: 0;background: none;display: flex;justify-content: center;align-items: center;color: #858585;cursor: default;">资源库中没有视频资源！</li>')
    }

    var html = ''
    if (list && list.length > 0) {
      for (var i in list) {
        var item = list[i]
        html += render(item)
      }
    }
    if (append === true && list && list.length > 0) {
      filelistDom.append(html)
    } else if (append === false && list && list.length > 0) {
      filelistDom.html(html)
    }

    if (end === true) {
      filelistDom.append('<li style="width: 100%;height: 40px;margin: 0;padding: 0;background: none;display: flex;justify-content: center;align-items: center;color: #858585;cursor: default;">没有了</li>')
    }

    function render (obj) {
      var original = obj.original
      var repertoryid = obj.repertoryid
      var title = obj.title
      var url = obj.url
      var html = '';
      html += '<li class="chooseVideo" id="repertoryid-' + repertoryid + '" data-id="' + repertoryid + '" data-url="' + url + '" data-original="' + original + '" data-title="' + title + '" title="' + title + '">';
      html += '<p class="title">' + title + '</p>';
      html += '<p class="imgWrap">';
      html += '<img src="" />';
      html += '</p>';

      html += '</li>';

      return html;
    }
  }

  $(function () {
    if (!editor) {
      console.error('editor empty');
    }

    var $fileList = $('#queueList .filelist')

    // 定义翻页页面参数
    var page = 1;
    // 总数据
    var total = -1;
    // 已经加载的数据
    var totalRender = -1;
    // 是否再请求当前
    var requesting = false;
    // 选中的视频数据信息
    var video = {
      id: -1,
      src: '',
      title: ''
    };
    // 上传的动作
    var uploader = null;

    // 请求获取video数据列表
    function videlList (page, append, completeFunc) {
      var requestParam = {
        page: page,
        size: 12
      }
      $fileList.append('<li class="loading" style="width: 100%;height: 40px;margin: 0;padding: 0;background: none;display: flex;justify-content: center;align-items: center;color: #858585;cursor: default;">Loading...</li>')
      request.get(editor.getActionUrl(editor.getOpt('videoManagerActionName')), requestParam, function (rsp) {
        if (rsp.state === 'SUCCESS') {
          if (total === -1 && parseInt(rsp.total) === 0) {
            total = 0;
            totalRender = 0;
            renderVideoList({
              filelistDom: $fileList,
              empty: true
            })
            return;
          }
          var list = rsp.list
          renderVideoList({
            filelistDom: $fileList,
            list: list,
            append: append
          })

          if (total === -1) {
            total = rsp.total
          }

          if (totalRender === -1) {
            totalRender = 0;
          }
          totalRender += (list.length ? list.length : 0)

          if (totalRender === total) {
            renderVideoList({
              filelistDom: $fileList,
              end: true
            })
          }
        }

        $fileList.children('.chooseVideo').off();
        $fileList.children('.chooseVideo').on('click', function () {
          var _this = $(this);
          $fileList.children('.cur').removeClass('cur');
          _this.addClass('cur');
          video = {
            id: _this.data('id'),
            src: _this.data('url'),
            title: _this.data('original')
          }
        })
      }, null, function () {
        $fileList.find('.loading').remove();
        if (typeof completeFunc === 'function') {
          completeFunc()
        }
      })
    }

    function initVidelList () {
      page = 1;
      // 总数据
      total = -1;
      // 已经加载的数据
      totalRender = -1;
      // 是否再请求当前
      requesting = false;
      // 选中的视频数据信息
      video = {
        id: -1,
        src: '',
        title: ''
      };
      // 方法的执行
      videlList(page, false);
    }
    initVidelList()

    $fileList.scroll(function () {
      var scrollHeight = $fileList[0].scrollHeight;
      var clientHeight = $fileList[0].clientHeight;
      var scrollTop = $fileList.scrollTop();
      if (scrollHeight - (scrollTop + clientHeight) < 1 && requesting === false && (total === -1 || totalRender < total)) {
        // 到底了
        requesting = true;
        videlList(++page, true, function () {
          requesting = false
        });
      }
    })

    // 弹窗确认按钮
    dialog.onok = function () {
      if (video && video.id && video.id > 0) {
        var widthVal = $('#upload_width').val();
        var heightVal = $('#upload_height').val();
        var width = !isNaN(parseInt(widthVal)) && parseInt(widthVal) > 0 ? parseInt(widthVal) : 'auto';
        var height = !isNaN(parseInt(heightVal)) && parseInt(heightVal) > 0 ? parseInt(heightVal) : 'auto';

        if (/\d+%$/.test(widthVal)) {
          width = width + '%';
        } else if (/\d+px$/.test(widthVal)) {
          width = width + 'px';
        } else if (/\d+em$/.test(widthVal)) {
          width = width + 'em';
        } else if (/\d+rem$/.test(widthVal)) {
          width = width + 'rem';
        } else if (/\d+vh$/.test(widthVal)) {
          width = width + 'vh';
        }

        if (/\d+%$/.test(heightVal)) {
          height = height + '%';
        } else if (/\d+px$/.test(heightVal)) {
          height = height + 'px';
        } else if (/\d+em$/.test(heightVal)) {
          height = height + 'em';
        } else if (/\d+rem$/.test(heightVal)) {
          height = height + 'rem';
        } else if (/\d+vh$/.test(heightVal)) {
          height = height + 'vh';
        }

        var align = $("input[name='video_align']:checked").val();
        editor.execCommand('insertvideo', {
          id: video.id,
          cryptoid: getVueFunc('CRYPTO_EN')('' + video.id),
          src: video.src,
          width: width,
          height: height,
          align: align
        });
      }
    };
    // 弹窗关闭按钮
    dialog.oncancel = function () {
      page = 1;
      total = -1;
      totalRender = -1;
      requesting = false;
      video = {
        id: -1,
        src: '',
        title: ''
      };
      uploader = null;
    };

    if (!WebUploader) {
      return;
    }
    // 显示允许上传视频的大小
    var allowSize = parseFloat(editor.getOpt('videoMaxSize') / 1024 / 1024).toFixed(1);
    $('#gAllowUploadVideoSize').html(allowSize + 'M')
    // 上传的动作
    uploader = WebUploader.create({
      pick: {
        id: '#gVideoPickerReady',
        label: '上传视频'
      },
      accept: {
        title: 'Video',
        extensions: 'mp4',
        mimeTypes: 'video/mp4'
      },
      swf: '../../third-party/webuploader-0.1.5/Uploader.swf',
      server: editor.getActionUrl(editor.getOpt('videoActionName')),
      fileVal: editor.getOpt('videoFieldName'),
      duplicate: true,
      fileSingleSizeLimit: editor.getOpt('videoMaxSize'),
      compress: false,
      auto: true,
      runtimeOrder: 'html5'
    });
    uploader.on('uploadBeforeSend', function (file, data, header) {
      // 这里可以通过data对象添加POST参数
      header['Authorization'] = getQueryVariable('jsessionid');
      $('#queueList  .progress').show()
    });
    uploader.on('uploadProgress', function (file, percentage) {
      var progress = parseFloat(percentage * 100).toFixed(2)
      $('#queueList  .progress .text').html(progress + '%')
      $('#queueList  .progress .percentage').attr('style', 'width: ' + progress + '%;')
    });
    uploader.on('uploadComplete', function (file, code) {
      $('#queueList  .progress').hide()
    });
    uploader.on('error', function (code) {
      if (code === 'F_EXCEED_SIZE') {
        getVueFunc('IFRAME_MESSAGE_ERROR')('超出允许上传视频的大小！')
      }
      $('#queueList  .progress').hide()
    });
    uploader.on('uploadSuccess', function (file, ret) {
      if (ret.code !== 200) {
        var message = ret.message && ret.message.message ? ret.message.message : '';
        if (message) {
          getVueFunc('IFRAME_MESSAGE_ERROR')(message)
        }
      } else {
        if (ret.data && parseInt(ret.data) === 1) {
          $fileList.hide(300, function () {
            initVidelList()
            $fileList.show(300)
          })
        }
      }
    });
  });
  // eslint-disable-next-line no-undef
})(window, jQuery);
